export default class Toolkit {
    // 确保是数组
    static ensure (val, def = []) {
        return Array.isArray(val)
            ? val
            : this.isNull(val) || this.isUndef(val) || this.isEmptyString(val)
                ? def : [val]
    }

    // 分页
    static pagination (source, options = {}, filter = null) {
        const opts = Object.assign({ page: 1, size: 10, field: 'order' }, options)
        return source.map((item, dex) =>
            Object.assign({
                [opts.field]: (opts.page - 1) * opts.size + (dex + 1)
            },
            this.isFunction(filter) ? filter.call(this, item) : item
            )
        )
    }

    // 判断是否是function
    static isFunction (fn) {
        return typeof fn === 'function'
    }

    // 判断是否是undefined
    static isUndef (val) {
        return arguments.length === 1 && val === undefined
    }

    // 判断是否是Object
    static isObject (obj) {
        const toString = {}.toString
        return toString.call(obj) === '[object Object]'
    }

    // 判断是否是Object
    static isPlainObject (obj) {
        const hasOwnProp = Object.hasOwnProperty
        if (!obj || this.isObject(obj) === false) {
            return false
        }
        const proto = Object.getPrototypeOf(obj)
        if (!proto) {
            return true
        }
        const Ctor = hasOwnProp.call(proto, 'constructor') && proto.constructor
        return (
            typeof Ctor === 'function' &&
            hasOwnProp.toString.call(Ctor) === hasOwnProp.toString.call(Object)
        )
    }

    // 判断是否是null
    static isNull (val) {
        return val === null
    }

    // 判断是否是空字符
    static isEmptyString (val) {
        return val === ''
    }

    // 判断是否是String
    static isString (val) {
        return typeof val === 'string'
    }

    // 判断是否是序列化对象
    static serialize (obj) {
        return this.isPlainObject(obj)
            ? Object.keys(obj)
                .reduce((a, c) => {
                    if (!this.isUndef(obj[c]) || !this.isNull(obj[c])) {
                        a.push(c + '=' + obj[c])
                    }
                    return a
                }, [])
                .join('&')
            : ''
    }

    // 判断是否是空数组
    static isEmptyArray (ary) {
        return Array.isArray(ary) && ary.length === 0
    }

    // eval的替代方案
    static evil (fn) {
        return new Function('return  ' + fn)()
    }
}
